<?php

namespace app\admin\controller;
use app\admin\model\Config;
use think\Controller;

/**
 *
 * 角色管理
 * @author fenghao <303529990@qq.com>
 */
class Amusement extends Base
{
    public function lists(){
        if(request()->isAjax()){
            $this->_param['page']  = isset($this->_param['page'])?$this->_param['page']:1;
            $this->_param['limit'] = isset($this->_param['limit'])?$this->_param['limit']:10;
            $list = db('v_question_house')
            ->where($this->_map)->order('id desc');
            if(!empty($this->_param['user'])){
                $list = $list->where('incode',$this->_param['user']);
            }
            $_list = clone($list);
            $total = $list->count();//print_r(Db::name('member')->getLastSql());die;
            $list = $_list;
            $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
            $data = $list->select();
            $this->ajaxReturn('',$data,$total);
        }else{
            return $this->fetch();
        }
    }
   public function question(){
       if(request()->isAjax()){
           $this->_param['page'] = isset($this->_param['page'])?$this->_param['page']:1;
           $this->_param['limit'] = isset($this->_param['limit'])?$this->_param['limit']:10;
           $list = db('question')->where($this->_map)->order('id desc');
           if(!empty($this->_param['incode'])){
               $list = $list->where('incode',$this->_param['incode']);
           }
           $_list = clone($list);
           $total = $list->count();//print_r(Db::name('member')->getLastSql());die;
           $list = $_list;
           $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
           $data = $list->select();
           foreach ($data as $k=>$v){
               $question = unserialize($v['question']);
               $data[$k]['question'] = $question;
           }
           $this->ajaxReturn('',$data,$total);
       }else{
           $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
           $load_excel = $http_type.$_SERVER['HTTP_HOST'].'/excel/excel_tpl/question_tpl.xlsx';;
           $this->assign('load_excel',$load_excel);
           return $this->fetch();
       }
   }

   //添加角色
   public function add()
   {
   
       return $this->_edit();
   }
   
   /**
    * 修改问题
    * @return type
    */
   public function edit($id)
   {
       return $this->_edit($id);
   }
   
   private function _edit($id = '')
   {
       //print_r($this->_param);die;
       if ($this->request->isPost()) {
           $param = $this->_param;
           $param['question1'] = $this->_param['question'][1];
           $param['question2'] = $this->_param['question'][2];
           $param['question3'] = $this->_param['question'][3];
           $param['question4'] = $this->_param['question'][4];
           $rule = [
               ['content', 'require', '题目不能为空'],
               ['answer', 'require', '答案不能为空'],
               ['question1', 'require', '选项不能为空'],
               ['question2', 'require', '选项不能为空'],
               ['question3', 'require', '选项不能为空'],
               ['question4', 'require', '选项不能为空'],
           ];
           $msg = $this->validate($param, $rule);
           if ($msg !== true) {
               $this->error($msg, '');
           }
           $this->_param['question'] = serialize($this->_param['question']);
           if(empty($id)){
               $this->_param['create_time'] = time();
               $re = db('question')->insert($this->_param);
           }else{
               $re = db('question')->where('id',$id)->update($this->_param);
           }
           if ($re) {
               $this->success(empty($id) ? '新增成功!' : '更新成功!', url('lists'));
           } else {
               $this->error('编辑失败', '');
           }
       }
   }
   
   //批量删除用户
   public function del($id)
   {
       if(empty($id))$this->error('删除失败!', '');
       $res = db('question')->where('id','in',$id)->delete();
       if ($res !== false) {
   
           $this->success('删除成功!', url('lists'));
       } else {
           $this->error('删除失败!', '');
       }
   }
   public function excel_upload(){
       // EXCEL 文件上传
       if (empty ( $_FILES ['file_'] ['name'] )) {
           $return = array(
               'state'=>false,
               'msg'=>"请选择需要上传excel文件！"
           );
           echo json_encode($return);
           exit();
       }
        
       $tmp_file = $_FILES ['file_'] ['tmp_name'];
       $file_types = explode ( ".", $_FILES ['file_'] ['name'] );
       $file_type = $file_types [count ( $file_types ) - 1];
       if (strtolower ( $file_type ) != "xlsx") {
           $return = array(
               'state'=>false,
               'msg'=>"不是excel文件，重新稍后上传"
           );
           echo json_encode($return);
           exit();
       }
        
       $savePath = $_SERVER['DOCUMENT_ROOT'].'/excel/'; // 设置上传路径
       if(!file_exists($savePath)){
           @mkdir($savePath, 0777, true);
       }
       $str = date ( 'YmdHis' ) . uniqid (); // 以时间来命名上传的文件
       $file_name = $str . "." . $file_type; // 是否上传成功
       if (! copy ( $tmp_file, $savePath . $file_name )) {
           $return = array(
               'state'=>false,
               'msg'=>"excel上传失败，请稍后重新上传"
           );
           echo json_encode($return);
           exit();
       }
   
       echo json_encode(array('state'=>true,'name'=>$str));exit;
   }
   public function import(){
       $excelpath = $this->_param['name'];
       $this->assign('excel_name',json_encode($excelpath));
       return  $this->fetch('common/file_handle');
       exit;
       $condition = $this->_param;
       set_time_limit(0);
       // 读取EXCEL文件
       
       Vendor('phpexcel.PHPExcel');//调用类库,路径是基于vendor文件夹的
       Vendor('phpexcel.PHPExcel.Worksheet.Drawing');
       Vendor('phpexcel.PHPExcel.Writer.Excel2007');
       $objExcel = new \PHPExcel();
       //set document Property
       $objWriter = \PHPExcel_IOFactory::createReader('Excel2007');
       $excelpath = $_SERVER['DOCUMENT_ROOT'].'/excel/'.$condition['name'].'.xlsx';
       $data = [
           'name'=>$excelpath,'create_time'=>time()
       ];
       db('import_log')->insert($data);exit;
       $objPHPExcel = $objWriter->load ( $excelpath );
       $sheet = $objPHPExcel->getSheet ( 0 );
       $rows = $sheet->getHighestRow (); // 取得总行数
      
       //print_r($rows);die;
       
       // 数据处理
       $datas = array ();
       $delete_row = array ();
       $excel = array ();
       $is_download = false;
       //正确和错误条数计数
       $add_num = 0;
       $edit_num = 0;
       $error_num = 0;
       //当前执行位置
       $now_run = 1;
       $percent = 0;
       ob_clean();
       ob_start();
       echo "<script language='javascript'>" .
           '$("#box").append("'."<p class='pos-r text-overflow'><i class='fa fa-play-circle-o c-success'></i>:"."[".date('H:i:s')."]，开始处理。"."</p>\");".
           '$'."('.progress_bar .number-pb').NumberProgressBar().reach($percent);" .
           "</script>";
       ob_end_flush();
       ob_flush();
       flush();
       for($i = 2; $i <= $rows; $i ++) {
           $flag = false;
           $cs_name = '';
           $now_run++;
           $percent = intval(($now_run/$rows)*100);
           ob_clean();
           ob_start();
           $error_msg = '';$question = [];$excel = [];
           // 名称<必填>
           $excel ['content'] = $objPHPExcel->getActiveSheet ()->getCell ( "A{$i}" )->getValue ();
           if (empty( $excel ['content'] )) {
               $flag = true;
               $error_msg = !!$error_msg ? $error_msg."、题目为必填" : $error_msg.'题目为必填';
           }
           //答案
           $question[1] = $objPHPExcel->getActiveSheet ()->getCell ( "B{$i}" )->getValue ();
           if (empty( $question[1] )) {
               $flag = true;
               $error_msg = !!$error_msg ? $error_msg."、选项1为必填" : $error_msg.'选项1为必填';
           }
           $question[2] = $objPHPExcel->getActiveSheet ()->getCell ( "C{$i}" )->getValue ();
           if (empty( $question[2] )) {
               $flag = true;
               $error_msg = !!$error_msg ? $error_msg."、选项2为必填" : $error_msg.'选项2为必填';
           }
           $question[3] = $objPHPExcel->getActiveSheet ()->getCell ( "D{$i}" )->getValue ();
           if (empty( $question[3] )) {
               $flag = true;
               $error_msg = !!$error_msg ? $error_msg."、选项3为必填" : $error_msg.'选项3为必填';
           }
           $question[4] = $objPHPExcel->getActiveSheet ()->getCell ( "E{$i}" )->getValue ();
           if (empty( $question[4] )) {
               $flag = true;
               $error_msg = !!$error_msg ? $error_msg."、选项4为必填" : $error_msg.'选项4为必填';
           }
           $excel ['answer'] = $objPHPExcel->getActiveSheet ()->getCell ( "F{$i}" )->getValue ();
           if (empty( $excel ['answer'] )) {
               $flag = true;
               $error_msg = !!$error_msg ? $error_msg."、答案为必填" : $error_msg.'答案为必填';
           }
           if (! $flag) {
                // 保存数据
                   $excel ['question'] = serialize($question);
                   $excel ['create_time'] = time();
                   $result = db('question')->insert($excel);
                   $add_num++;
                   echo "<script language='javascript'>" .
                       '$'."('.progress_bar .number-pb').NumberProgressBar().reach($percent);" .
                       "location.href = '#anchor';" .
                       "</script>";
                   unset($excel);
                   $delete_row [] = $i; // 记录插入成功的当前行
               
           } else { // 有错误的EXCEL行
               $is_download = true;
               $objPHPExcel->getActiveSheet()->setCellValue("G{$i}",$error_msg);
               $error_num++;
               echo "<script language='javascript'>" .
                   '$'."('.progress_bar .number-pb').NumberProgressBar().reach($percent);" .
                   "location.href = '#anchor';" .
                   "</script>";
               unset($excel);
           }
           ob_end_flush();
           ob_flush();
           flush();
       }
       ob_clean();
       ob_start();
       echo "<script language='javascript'>" .
           '$("#box").append("'."<p id='waitting' class='pos-r text-overflow'><i class='fa fa-spinner fa-spin fa-pulse'></i>:"."[".date('H:i:s')."]，导入成功，正在生成错误列表excel，请稍等。。。"."</p>\");".
           "</script>";
       ob_end_flush();
       ob_flush();
       flush();
       $delete_row = array_reverse ( $delete_row );
       foreach ( $delete_row as $v ) {
           $objPHPExcel->getActiveSheet ()->removeRow ( $v );
       }
       
       // 删除原EXCEL文件
       if (file_exists ( $excelpath )) {
           unlink ( $excelpath );
       }
       
       // 如有错误下载错误的文件
       if ($is_download) { // 存在格式不成功excel，下载
           $objPHPExcel->getActiveSheet()->setCellValue("G1",'错误信息');
           $filenames = 'import_error' . date ( 'YmdHis' );
           $filename = $_SERVER['DOCUMENT_ROOT'].'/excel/'.$filenames.'.xlsx';
           $filename = str_replace('\\', '/', trim($filename));
           ob_end_clean ();
           $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
           $objWriter->save ($filename);
           $download_error = $filename;
           echo "<script language='javascript'>" .
               '$("#box #waitting").html("'."<i class='fa fa-power-off c-primary'></i>:".'['.date('H:i:s')."]，处理结束。\");".
               "location.href = '#anchor';" .
               '$(".btnr").click();' .
               '$("#game_over").append("'."<p>导入".($rows-1)."条，新增{$add_num}条，修改{$edit_num}条，失败{$error_num}条。<a class='c-orange' href='".$download_error."'>下载错误列表</a></p>\");".
               "</script>";
       }else{
           echo "<script language='javascript'>" .
               '$("#box #waitting").html("'."<i class='fa fa-power-off c-primary'></i>:".'['.date('H:i:s')."]，处理结束。\");".
               "location.href = '#anchor';" .
               '$(".btnr").click();' .
               '$("#game_over").append("'."<p>导入".($rows-1)."条，新增{$add_num}条，修改{$edit_num}条，失败{$error_num}条。</p>\");".
               "</script>";
       }
       // 无错误
       exit();
   }
   
   public function grade(){
       $data = db('config')->where('group',2)->select();
       $lists = [];
       foreach ($data as $k=>$v){
           $lists[$v['name']] = $v['value'];
       }
       $this->assign('lists',$lists);
       return $this->fetch();
   }
   public function grade_edit(){
       if(!empty($this->_param)){
           $config = new Config();
           foreach ($this->_param as $k=>$v){
               if(trim($v)!=''){
                   if($config->GET(['name'=>$k])){
                       $config->where(['name'=>$k])->update(['value'=>$v]);
                   }else{
                       $config->insert(['name'=>$k,'value'=>$v,'group'=>2]);
                   }
   
               }
           }
   
       }
       $this->success('设置完成!', url('grade'));
   }
   public function sign_set(){
       if ($this->request->isPost()) {
          
           $data = $this->_param['day'];
           //print_r($this->_param);
           foreach ($data as $k=>$v){
               $check = db('sign')->where('days',$k)->find();
               if(!empty($check)){
                   db('sign')->where('days',$k)->update(['reward'=>$v]);
               }else{
                   db('sign')->insert(['reward'=>$v,'days'=>$k]);
               }
           }
           $this->success('更新成功!', url('sign_set'));
       }else{
           $lists = db('sign')->select();
           $lists = array_column($lists,'reward','days');
           $this->assign('lists',$lists);
           return $this->fetch();
       }
       
   }
}
